'use strict';

const Controller = require('egg').Controller;

class ShortConnection extends Controller {

  async redisCreate() {
    this.ctx.validate({
      url: {
        type: 'string',
        format: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/,
      },
      length: {
        type: 'number',
        default: 5,
        min: 5,
        max: 10,
        convertType: 'number',
        required: false,
      },
    }, this.ctx.query);
    const { url, length } = this.ctx.query;
    const data = await this.ctx.service.shortConnection.index.redisCreate(url, length);
    this.ctx.sendSuccess(data);
  }

  async redisGet() {
    this.ctx.validate({
      id: {
        type: 'string',
      },
    }, this.ctx.params);
    const { id } = this.ctx.params;
    await this.ctx.service.shortConnection.index.redisGet(id);
  }

  async mongoCreate() {
    this.ctx.validate({
      url: {
        type: 'url',
      },
      length: {
        type: 'number',
        default: 5,
        min: 5,
        max: 10,
        convertType: 'number',
        required: false,
      },
    }, this.ctx.query);
    const { url, length } = this.ctx.query;
    const data = await this.ctx.service.shortConnection.index.mongoCreate(url, length);
    this.ctx.sendSuccess(data);
  }

  async mongoGet() {
    this.ctx.validate({
      id: {
        type: 'string',
      },
    }, this.ctx.params);
    const { id } = this.ctx.params;
    await this.ctx.service.shortConnection.index.mongoGet(id);
  }
}

module.exports = ShortConnection;
